package pl.edu.agh.logview.webservice;
import java.sql.SQLException;
import java.util.Calendar;

import javax.jws.WebParam;
import javax.jws.WebService;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

import pl.edu.agh.logview.database.DbHelper;
import pl.edu.agh.logview.model.Message;
import pl.edu.agh.logview.model.State;
import pl.edu.agh.logview.model.helper.MessageHelper;
import pl.edu.agh.logview.model.helper.StateHelper;



@WebService(endpointInterface = "pl.edu.agh.logview.webservice.LogServerReceiver",
            serviceName = "LogServerReceiver")
public class LogServerReceiverImpl implements LogServerReceiver {
	DbHelper dbHelper = null;
	MessageHelper messageHelper = null;
	StateHelper stateHelper = null;
	
	private static final String RECEIVE = "ODEBRANIE";
	private static final String STATE = "STAN";
	
	public LogServerReceiverImpl(){
		dbHelper = new DbHelper();
		messageHelper = new MessageHelper();
		stateHelper = new StateHelper();
		
	}

	@Override
	public String pushMessage(@WebParam(name = "messageBean") MessageBean messageBean) {
		if(messageBean.getType().equals(RECEIVE)){
			Message message = messageHelper.buildMessage((MessageBeanImpl)messageBean);
			
			try {
				dbHelper.getMessageDao().createIfNotExists(message);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		else if(messageBean.getType().equals(STATE)){
			State state = stateHelper.buildState((MessageBeanImpl)messageBean);
			try {
				dbHelper.getStateDao().createIfNotExists(state);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
		System.out.println("RECEIVER : " + ReflectionToStringBuilder.toString(messageBean));
		//System.out.println("Time : " + messageBean.getTime());
		return ReflectionToStringBuilder.toString(messageBean);
	}

	@Override
	public long checkTime() {
		
		return Calendar.getInstance().getTimeInMillis();
	}

}